package com.lancoo.ccas52.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lancoo.ccas52.aspect.LogAnnotation;
import com.lancoo.ccas52.entity.*;
import com.lancoo.ccas52.mapper.PeriodSchemeMapper;
import com.lancoo.ccas52.pojo.response.basicPlatform.*;
import com.lancoo.ccas52.pojo.response.request.ProxyUrl;
import com.lancoo.ccas52.pojo.vo.MsgCoursePlanExamine;
import com.lancoo.ccas52.pojo.vo.MsgTimeAdjustment;
import com.lancoo.ccas52.service.*;
import com.lancoo.ccas52.util.ResponseObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName YunController
 * @Description 基础平台接口
 * @Author quin
 * @Date 2022/12/29 16:02
 */
@Slf4j
@Api(tags = "基础平台相关接口")
@RestController
@RequestMapping("/api/v5.2.1/pc/yun")
public class YunController {

    @Resource
    private YunBasicService yunBasicService;
    @Resource
    private TaskInfoService taskInfoService;
    @Resource
    private MajorService majorService;
    @Resource
    private PlanTeachingService planTeachingService;
    @Resource
    private TeacherService teacherService;
    @Resource
    private StudentService studentService;
    @Resource
    private PeriodSchemeMapper periodSchemeMapper;
    @Resource
    private TaskToGradeService taskToGradeService;


    @ApiOperation("获取子系统地址")
    @GetMapping("/getSystemUrl")
    public ResponseObject<String> getSystemUrl(@ApiParam(value = "系统id，null获取基础平台地址", required = false) @RequestParam(required = false) String sysId) {
        SubSystemsMainServer subSystemsMainServer = yunBasicService.getSubSystemsMainServer(sysId, false);
        return ResponseObject.ofSuccess(subSystemsMainServer.getWebSvrAddr());
    }

    @ApiOperation("获取基础平台学校历史学期")
    @GetMapping("/getTermInfo/{schoolId}")
    public ResponseObject<List<TermBasicInfo>> getTermInfo(@ApiParam(value = "学校Id", required = true) @PathVariable String schoolId) {
        return ResponseObject.ofSuccess(yunBasicService.getAllTermInfo(schoolId));
    }

    @ApiOperation("获取当前学期")
    @GetMapping("/getCurrentTermInfo/{schoolId}")
    public ResponseObject<CurrentTermInfo> getCurrentTermInfo(@ApiParam(value = "学校Id", required = true) @PathVariable String schoolId) {
        return ResponseObject.ofSuccess(yunBasicService.GetCurrentTermInfo(schoolId));
    }

    @ApiOperation("同步基础平台教学计划")
    @PostMapping("/syncPlanTeaching")
    public ResponseObject<String> syncPlanTeaching(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                                   @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId,
                                                   @ApiParam(value = "学期", required = true) @RequestParam String term) {
//        //数据库教学计划为空时才会执行同步逻辑
//        if (planTeachingService.lambdaQuery().eq(PlanTeaching::getTaskId, taskId).count() != 0) {
//            return ResponseObject.ofSuccess("已经同步过教学计划");
//        }
        List<String> gradeList = taskToGradeService.lambdaQuery().eq(TaskToGrade::getTaskId, taskId).list()
                .stream().map(TaskToGrade::getGradeId).collect(Collectors.toList());
        return ResponseObject.ofSuccess(yunBasicService.syncPlanTeaching(taskId, schoolId, term, gradeList));
    }

    @ApiOperation("同步基础平台教室")
    @GetMapping("/syncRoom")
    public ResponseObject<String> syncRoom(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                           @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId,
                                           @ApiParam(value = "学期", required = true) @RequestParam String term) {
        return ResponseObject.ofSuccess(yunBasicService.syncRoom(taskId, schoolId, term));
    }

    @ApiOperation("同步年级专业")
    @GetMapping("/syncMajor")
    public ResponseObject<String> syncMajor(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                            @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId,
                                            @ApiParam(value = "学期", required = true) @RequestParam String term) {
        if (majorService.lambdaQuery().eq(Major::getTaskId, taskId).count() == 0) {
            List<String> gradeList = taskToGradeService.lambdaQuery().eq(TaskToGrade::getTaskId, taskId).list()
                    .stream().map(TaskToGrade::getGradeId).collect(Collectors.toList());
            yunBasicService.syncMajor(taskId, schoolId, term, gradeList);
            return ResponseObject.ofSuccess("同步专业信息成功");
        } else {
            return ResponseObject.ofSuccess("已经同步过专业信息");
        }
    }

    @ApiOperation("同步学生")
    @GetMapping("/syncStudent")
    public ResponseObject<String> syncStudent(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                              @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId) {
        if (studentService.lambdaQuery().eq(Student::getTaskId, taskId).count() == 0) {
            List<String> gradeList = taskToGradeService.lambdaQuery().eq(TaskToGrade::getTaskId, taskId).list()
                    .stream().map(TaskToGrade::getGradeId).collect(Collectors.toList());
            yunBasicService.syncStudent(taskId, schoolId, gradeList);
            return ResponseObject.ofSuccess("同步学生信息成功");
        } else {
            return ResponseObject.ofSuccess("已经同步过学生信息");
        }
    }

    @ApiOperation("同步教师")
    @GetMapping("/syncTeacher")
    public ResponseObject<String> syncTeacher(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                              @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId,
                                              @ApiParam(value = "学期", required = true) @RequestParam String term) {
        if (teacherService.lambdaQuery().eq(Teacher::getSchoolId, schoolId).eq(Teacher::getTerm, term).count() == 0) {
            yunBasicService.syncTeacher(taskId, schoolId, term);
            return ResponseObject.ofSuccess("同步教师成功");
        } else {
            return ResponseObject.ofSuccess("已经同步过教师");
        }
    }

    @ApiOperation("同步课时方案")
    @GetMapping("/syncPeriodScheme")
    public ResponseObject<String> syncPeriodScheme(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                                   @ApiParam(value = "0:小周  1:大周", required = false) @RequestParam(required = false, defaultValue = "0") Integer weekSet,
                                                   @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId,
                                                   @ApiParam(value = "学期", required = true) @RequestParam String term) {
        if (periodSchemeMapper.selectCount(new LambdaQueryWrapper<PeriodScheme>().eq(PeriodScheme::getSchoolId, schoolId).eq(PeriodScheme::getTerm, term)) == 0) {
            yunBasicService.syncPeriodScheme(taskId, weekSet, schoolId, term);
            return ResponseObject.ofSuccess("同步课时方案成功");
        } else {
            return ResponseObject.ofSuccess("已经同步过课时方案");
        }
    }


    @ApiOperation("同步基础平台课程库")
    @GetMapping("/syncCourse")
    public ResponseObject<String> syncCourse(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                             @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId) {
        TaskInfo taskInfo = taskInfoService.getById(taskId);
        return ResponseObject.ofSuccess(yunBasicService.syncCourse(taskId, schoolId, taskInfo.getTerm()));
    }

    @ApiOperation("同步基础平台环节库")
    @GetMapping("/syncSegment")
    public ResponseObject<String> syncSegment(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                              @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId) {
        TaskInfo taskInfo = taskInfoService.getById(taskId);
        return ResponseObject.ofSuccess(yunBasicService.syncSegment(taskId, schoolId, taskInfo.getTerm()));
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/getUserInfo")
    public ResponseObject<UserInfo> getUserInfo(@ApiParam(value = "用户id", required = true) @RequestHeader String userId) {
        return ResponseObject.ofSuccess(yunBasicService.getUserInfo(userId));
    }

    @ApiOperation("获取加密锁信息")
    @GetMapping("/getLockInfo")
    public ResponseObject<LockerInfo> geLockerInfo(@ApiParam(value = "学校Id", required = true) @RequestParam String schoolId) {
        return ResponseObject.ofSuccess(yunBasicService.getSubSystemLockerInfoByID(schoolId));
    }

    @ApiOperation("根据token获取用户信息")
    @GetMapping("/getUserDetailInfoByToken")
    public ResponseObject<UserInfo> getUserDetailInfoByToken(@ApiParam(value = "token", required = true) @RequestHeader("Authorization") String token,
                                                             @ApiParam(value = "任务id", required = false) @RequestHeader(required = false) Integer taskId) {
        UserInfo userInfoByToken = yunBasicService.getUserInfoByToken(token, taskId);
        return ResponseObject.ofSuccess(userInfoByToken);
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public ResponseObject<Integer> logout(@ApiParam(value = "token", required = true) @RequestHeader("Authorization") String token,
                                          @ApiParam(value = "用户id", required = true) @RequestHeader String userId) {
        return ResponseObject.ofSuccess(yunBasicService.logout(userId, token));
    }

    @ApiOperation("同步课表至基础平台-在线选课")
    @GetMapping("/syncOnlineScheduleToBasic")
    @LogAnnotation(operationType = "13", operationContent = "同步教学班至基础平台")
    public ResponseObject syncTeachingClass(@ApiParam(value = "任务id", required = true) @RequestHeader Integer taskId,
                                            @ApiParam(value = "用户id", required = true) @RequestHeader String userId,
                                            @ApiParam(value = "用户名字", required = true) @RequestHeader String userName,
                                            @ApiParam(value = "学校id", required = true) @RequestParam String schoolId) {
        return yunBasicService.syncOnlineScheduleToBasic(taskId, userId, userName, schoolId);
    }

    @ApiOperation("同步课表至基础平台-课表编排")
    @GetMapping("/syncScheduleToBasic")
    @LogAnnotation(operationType = "13", operationContent = "同步课表至基础平台")
    public ResponseObject syncScheduleToBasic(@ApiParam(value = "任务id", required = true) @RequestHeader Integer taskId,
                                              @ApiParam(value = "用户id", required = true) @RequestHeader String userId,
                                              @ApiParam(value = "用户名字", required = true) @RequestHeader String userName,
                                              @ApiParam(value = "学校id", required = true) @RequestParam String schoolId) {
        return yunBasicService.syncAllScheduleToBasic(taskId, userId, userName, schoolId);
    }


    @ApiOperation("根据用户ID获取其身份")
    @GetMapping("/getIdentityTypeByUserID")
    public ResponseObject<List<IdentifyType>> getIdentityTypeByUserId(@ApiParam(value = "用户id", required = true) @RequestHeader String userId,
                                                                      @ApiParam(value = "token", required = true) @RequestHeader("Authorization") String token) {
        return ResponseObject.ofSuccess(yunBasicService.getIdentityTypeByUserID(userId, token));
    }


    @ApiOperation("开课计划变更审核")
    @PostMapping("/sendCoursePlanExamineResultMsg")
    public ResponseObject<Object> sendCoursePlanExamineResultMsg(@ApiParam(value = "开课计划变更审核实体类", required = true) @RequestBody MsgCoursePlanExamine msgCoursePlanExamine) {
        yunBasicService.sendCoursePlanExamineResultMsg(msgCoursePlanExamine);
        return ResponseObject.ofSuccess();
    }

    @ApiOperation("处理时段调整")
    @PostMapping("/sendTimeAdjustmentMsg")
    public ResponseObject<Object> sendTimeAdjustmentMsg(@ApiParam(value = "处理时段调整实体类", required = true) @RequestBody MsgTimeAdjustment msgTimeAdjustment) {
        yunBasicService.sendTimeAdjustmentMsg(msgTimeAdjustment);
        return ResponseObject.ofSuccess();
    }

    @ApiOperation("处理时段结束")
    @PostMapping("/sendTimeAdjustmentEndMsg")
    public ResponseObject<Object> sendTimeAdjustmentEndMsg(@ApiParam(value = "处理时段调整实体类", required = true) @RequestBody MsgTimeAdjustment msgTimeAdjustment) {
        yunBasicService.sendTimeAdjustmentEndMsg(msgTimeAdjustment);
        return ResponseObject.ofSuccess();
    }

    @ApiOperation("转发请求")
    @PostMapping(value = "/proxy")
    @Deprecated
    public String proxyUrlRequest(@RequestBody ProxyUrl proxyUrl) {
        return yunBasicService.proxyRequest(proxyUrl.getUrl());
    }

    @ApiOperation("转发带token验证请求")
    @PostMapping(value = "/proxy2")
    @Deprecated
    public String proxyUrlRequest2(@RequestBody ProxyUrl proxyUrl, @CookieValue("lg_tk") String token) {
        return yunBasicService.proxyRequest2(proxyUrl.getUrl(), token);
    }

}
